package com.frxuexi.lib_base

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.frxuexi.lib_base.entity.LocalEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import java.io.File

abstract class BaseViewModel<UiIntent:IUiIntent>:ViewModel() {
    //存放管理意图的管道
    private val _uiIntent= Channel<UiIntent>(Channel.UNLIMITED)

    //可变的状态，用于更新UI
    private var _state= MutableStateFlow<UiState>(UiState.onLoading)
    val state: StateFlow<UiState>
        get() = _state

    init {
        viewModelScope.launch {
            _uiIntent.receiveAsFlow().collect{
                handleIntent(it)
            }
        }
    }

    /**
     * 处理意图
     */
    abstract fun handleIntent(it: UiIntent)


    /**
     * 发送意图
     */
    fun sendIntent(intent: UiIntent){
        viewModelScope.launch {
            _uiIntent.send(intent)
        }
    }

    /**
     * 网络请求
     */
    fun httpRequest(request:Flow<ApiResponse<Any>>,type: HttpType=HttpType.DEFAULT){
        viewModelScope.launch {
            request.flowOn(Dispatchers.IO)
                .catch {
                    Log.i("===",it.message.toString())
                }.collect{
                    if(it.statusCode==200){
                        _state.value=UiState.onSuccess(it.data?:it.datas,type)
                    }else{
                        _state.value=UiState.onError(it.msg!!)
                    }
                }
        }
    }

    /**
     * 网络请求
     */
    fun httpRequest2(request:Flow<BaseEntity<Any>>,type: HttpType=HttpType.DEFAULT){
        viewModelScope.launch {
            request.flowOn(Dispatchers.IO)
                .catch {
                    Log.i("===",it.message.toString())
                }.collect{
                    if(it.code==0){
                        _state.value=UiState.onSuccess(it.data,type)
                    }else{
                        _state.value=UiState.onError(it.msg!!)
                    }
                }
        }
    }

    /**
     * room请求
     */
    fun roomRequest(request:Flow<Any>,type: HttpType=HttpType.DEFAULT){
        viewModelScope.launch {
            request.flowOn(Dispatchers.IO)
                .catch {
                    Log.i("===",it.message.toString())
                }.collect{
                    if(it!=null){
                        _state.value=UiState.onLoading
                        _state.value=UiState.onSuccess(it,type)
                    }else{
                        _state.value=UiState.onError("操作错误")
                    }
                }
        }
    }

    /**
     * 下载apk
     */
    fun download(url:String,file:File){
        viewModelScope.launch {
            DownloadUtil.download(url,file)
                .flowOn(Dispatchers.IO)
                .catch {
                    Log.i("===",it.message.toString())
                }.collect{
                    _state.value=it
                }
        }
    }

    /**
     * 扫描本地文件
     */
    fun scanFile(file: File){
        viewModelScope.launch {
            try {
                val files = file.listFiles()
                val list = mutableListOf<LocalEntity>()
                for (file in files){
                    list.add(LocalEntity(file.name,file.absolutePath))
                }
                _state.value=UiState.onSuccess(list)
            }catch (ex:Exception){
                _state.value=UiState.onError(ex.message.toString())
            }
        }
    }
}